/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package edu.os.dao.zakharov.oracledao;

import edu.os.dao.zakharov.interfacedao.UsersDAO;
import edu.os.dao.zakharov.oracle.Registration;
import edu.os.dao.zakharov.oracle.Users;
import java.math.BigDecimal;
import java.rmi.RemoteException;
import javax.annotation.Resource;
import javax.ejb.*;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

@Stateless
@TransactionManagement(TransactionManagementType.CONTAINER)
public class OracleUsersDAO implements UsersDAO {

    @Resource
    private SessionContext sessionContext;
    
    @PersistenceContext(unitName = "OnlineStore-ejbPU")
    private EntityManager em;

    @Override
    @TransactionAttribute(TransactionAttributeType.REQUIRED)
    public BigDecimal addUser(String login, String password, BigDecimal idRegistration)
            throws RemoteException {

        if (idRegistration.equals(new BigDecimal(0))) {
            throw new EJBTransactionRolledbackException();
        }
        em.flush();
        Query query = null;
        try {

            query = em.createNativeQuery("select sq_USERS.nextval from dual");

            Users user = new Users((BigDecimal) query.getSingleResult());
            user.setLogin(login);
            user.setPassword(password);
            user.setIdRegistration(em.find(Registration.class, idRegistration));

            int updatedEntities = em.createNativeQuery("update SYSTEM.USERS set ID_REGISTRATION = ? "
                    + "where ID_USER = ?")
                    .setParameter(1, idRegistration)
                    .setParameter(2, (BigDecimal) query.getSingleResult())
                    .executeUpdate();

            em.persist(user);
           
            return (BigDecimal) query.getSingleResult();

        } catch (Exception e) {
            e.printStackTrace();
            sessionContext.setRollbackOnly();
            return new BigDecimal(0);
        }
    }

}
